package com.common.frame.utils


import android.annotation.SuppressLint
import android.app.Application
import android.graphics.Bitmap
import com.common.frame.cache.CacheManager
import com.common.frame.lifecycle.ActivityManager
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.hjq.toast.ToastUtils
import java.util.*


@SuppressLint("StaticFieldLeak")
object Utils {

    private var sApplication: Application? = null

    /**
     * 初始化工具类
     *
     * @param app 应用
     */
    fun init(app: Application) {
        sApplication = app
        ActivityManager.init(app)
        CacheManager.init(app)
        ToastUtils.init(app)

    }

    /**
     * 获取Application
     *
     * @return Application
     */
    val app: Application
        get() {
            if (sApplication != null) return sApplication as Application
            throw NullPointerException("u should init first")
        }

     fun isSpace(s: String?): Boolean {
        if (s == null) return true
        var i = 0
        val len = s.length
        while (i < len) {
            if (!Character.isWhitespace(s[i])) {
                return false
            }
            ++i
        }
        return true
    }

    fun String.encodeAsBitmap(width: Int, height: Int): Bitmap {
        val result = MultiFormatWriter().encode(this, BarcodeFormat.CODE_128, width, height, null)
        val w = result.width
        val h = result.height
        val pixels = IntArray(w * h)

    /*    for (y in 0 until h) {
            val offset = y * w
            for (x in 0 until w) {
                pixels[offset + x] = if (result.get(x, y)) -0x1000000 else -0x1
            }
        }*/
        for (y in 0 until h) {
            val offset = y * w
            for (x in 0 until w) {
                pixels[offset + x] = if (result.get(x, y)) (0xFFFFFFFF).toInt() else 0x00000000 // 修改此处，白色线条（0xFFFFFFFF）和透明背景（0x00000000）
            }
        }



        val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        bitmap.setPixels(pixels, 0, width, 0, 0, w, h)
        return bitmap
    }


}
